package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.FinanceQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.FinanceDao;
import cn.org.eshow.model.Finance;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("financeDao")
public class FinanceDaoHibernate extends GenericDaoHibernate<Finance, Integer> implements FinanceDao {

    public FinanceDaoHibernate() {
        super(Finance.class);
    }

    @Override
    public Page<Finance> search(FinanceQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setPageSize(query.getPagesize());
            rule.setOffset(query.getOffset());
        }
        return page(rule);
    }

    @Override
    public List<Finance> list(FinanceQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public long count(FinanceQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return count(Finance.class, rule);
    }

    public EnhancedRule setRule(EnhancedRule rule, FinanceQuery query) {
        if (query != null) {
            if (query.startUpdateTime != null)
                rule.add(Restrictions.ge("updateTime", query.startUpdateTime));
            if (query.endUpdateTime != null)
                rule.add(Restrictions.le("updateTime", query.endUpdateTime));
            if (!StringUtils.isEmpty(query.getOrder()))
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
        }
        return rule;
    }
}
